package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.ITaskClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/14 11:10
 * @Version 1.0
 */
@Service
@Slf4j
public class WmTaskServiceImpl implements WmTaskService {

    @Autowired
    private ITaskClient taskClient;
    @Autowired
    private AutoScanService autoScanService;

    private final static int TASK_TYPE = 10;
    private final static int PRORITY = 20;



    @Override
    public void addTask(WmNews wmNews) {
        Task task = new Task();
        task.setTaskType(TASK_TYPE);
        task.setPriority(PRORITY);
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        WmNews param = new WmNews();
        param.setId(wmNews.getId());
        task.setParameters(ProtostuffUtil.serialize(param));
        taskClient.addTask(task);
    }


    //@Scheduled(fixedRate = 5000)
    public void delayTaskExec(){
        log.info("开始来取执行任务");
        ResponseResult poll = taskClient.poll(TASK_TYPE, PRORITY);
        log.info("拉取任务返回数据：{}", JSON.toJSONString(poll));
        if(poll == null || poll.getCode() != 200 || poll.getData() == null){
            return;
        }
        Object data = poll.getData();
        String json = JSON.toJSONString(data);
        Task task = JSON.parseObject(json, Task.class);
        WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
        autoScanService.scan(wmNews.getId());
    }

}